package com.jamlu.framework.network;

import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.jamlu.framework.network.converter.FormGsonConverterFactory;
import com.jamlu.framework.utils.helper.NullStringToEmptyAdapterFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 *
 * Created by ljb on 2017/5/16.
 */

public class NetworkManager {
    private static Retrofit mRetrofit;
    private static boolean isDebug = true;//是否输出日志


    public static Retrofit getInstance(@NonNull String baseUrl,boolean isDebug) {
        NetworkManager.isDebug = isDebug;
        if (mRetrofit == null) {
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(genericClient())
                    .addConverterFactory(FormGsonConverterFactory.create(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create()))
//                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create()))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            return mRetrofit;
        } else {
            return mRetrofit;
        }
    }

    public static OkHttpClient genericClient() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request request = chain.request();
                if (!com.blankj.utilcode.util.NetworkUtils.isConnected()) {
                    return chain.proceed(request);
                } else {
                    throw new NoNetworkException(); //无网络直接返回
                }
            }

        });
        if (isDebug){
            //添加请求拦截器
            httpClientBuilder.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(@NonNull Chain chain) throws IOException {
                    Request request = chain.request();
                    if (request.body() != null) {
                        if (request.body() instanceof FormBody) {
                            StringBuilder body = new StringBuilder("{");
                            int paramNum = ((FormBody) request.body()).size();
                            for (int i = 0; i < paramNum; i++) {
                                String name = ((FormBody) request.body()).name(i);
                                String value = ((FormBody) request.body()).value(i);
                                body.append(name)
                                        .append("=")
                                        .append(value);
                                if (i != paramNum - 1) {
                                    body.append(",");
                                }
                            }
                            body.append("}");
                            Log.e("request", String.format("发送请求: %s\n参数：%s",
                                    request.url(), body.toString()));
                        } else {
                            Log.e("request", String.format("发送请求: %s",
                                    request.url()));
                        }
                    }

                    return chain.proceed(request);
                }
            });
            //添加响应结果拦截器
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    if (TextUtils.isEmpty(message)) return;
                    String s = message.substring(0, 1);
                    // 如果收到想响应是json才打印
                    if ("{".equals(s) || "[".equals(s)) {
                        Log.e("response", "收到响应: " + message);
                    }
                }
            });
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClientBuilder.addInterceptor(interceptor);
        }
        return httpClientBuilder.build();
    }


    public static List<MultipartBody.Part> filesToMultipartBody(List<File> files) {
        return filesToMultipartBody(files, null);
    }

    public static List<MultipartBody.Part> filesToMultipartBody(List<File> files, Map<String, String> params) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            if (file != null) {
                String name = file.getName();
                RequestBody requestBody = null;
                if (name.endsWith(".png") || name.endsWith(".jpg")) {
//                    Bitmap bitmap = decodeSampledBitmapFromFile(file,200,200);
                    //Bitmap zipImage = ImageUtils.compressBySampleSize(bitmap, 6, true);
                    try {
//                        if (name.endsWith(".png")) {
//                            requestBody = RequestBody.create(MediaType.parse("image/*"), ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.PNG));
//                        } else {
//                            requestBody = RequestBody.create(MediaType.parse("image/*"), ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.JPEG));
//                        }
                        if (name.endsWith(".png")) {
                            requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                        } else {
                            requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                        }
//                        bitmap.recycle();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                }
                if (requestBody != null) {
                    builder.addFormDataPart("file", file.getName(), requestBody);
                }
            }
        }
        if (params != null) {
            Set<Map.Entry<String, String>> entries = params.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        return builder.build().parts();
    }

    public static List<MultipartBody.Part> fileToMultipartBody(File file, Map<String, String> params) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        if (file != null) {
            String name = file.getName();
            RequestBody requestBody = null;
            if (name.endsWith(".png") || name.endsWith(".jpg")) {
//                    Bitmap bitmap = decodeSampledBitmapFromFile(file,200,200);
                //Bitmap zipImage = ImageUtils.compressBySampleSize(bitmap, 6, true);
                try {
//                        if (name.endsWith(".png")) {
//                            requestBody = RequestBody.create(MediaType.parse("image/*"), ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.PNG));
//                        } else {
//                            requestBody = RequestBody.create(MediaType.parse("image/*"), ImageUtils.bitmap2Bytes(bitmap, Bitmap.CompressFormat.JPEG));
//                        }
//                        bitmap.recycle();
                    if (name.endsWith(".png")) {
                        requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                    } else {
                        requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            }
            if (requestBody != null) {
                builder.addFormDataPart("file", file.getName(), requestBody);
            }
        }
        if (params != null) {
            Set<Map.Entry<String, String>> entries = params.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        return builder.build().parts();
    }
}
